from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Request, Form, Cookie 
from fastapi.responses import HTMLResponse, RedirectResponse
from sqlalchemy.orm import Session
from database import get_db
from models import User
from utils import (
    verify_password, 
    create_session, 
    validate_session,
    get_password_hash,
    update_user_settings
)
from core.logger import app_logger as logger
from templates import templates
from fastapi import Form
from urllib.parse import quote, unquote  # 添加URL编解码功能
from core.logger import app_logger as logger

router = APIRouter()

@router.get("/", response_class=HTMLResponse)
async def login_page(request: Request):
    SessionId = request.cookies.get("SessionId")
    UserName = request.cookies.get("UserName")
    
    # 解码用户名
    decoded_username = unquote(UserName) if UserName else None
    
    if SessionId and decoded_username and validate_session(SessionId, decoded_username):
        return RedirectResponse(url="/welcome")
        
    return templates.TemplateResponse("login.html", {"request": request})

@router.post("/login")
async def login(
    request: Request,
    UserName: str = Form(...),
    Password: str = Form(...),
    db: Session = Depends(get_db)
):
    # 查询所有匹配的用户名（可能有多个）
    users = db.query(User).filter(
        User.UserName == UserName,
        User.DeadTime == None  # 只允许未删除的用户登录
    ).all()
    
    # 检查是否有匹配的用户
    user = None
    for u in users:
        if verify_password(Password, u.Password):
            user = u
            break
    
    if not user:
        return templates.TemplateResponse("login.html", {
            "request": request,
            "error": "用户名或密码错误"
        })
    
    logger.info(UserName,"登录成功")
        
    response = RedirectResponse(url="/welcome", status_code=303)
    SessionId = create_session(UserName)
    
    # 只对中文进行编码（判断是否包含非ASCII字符）
    def safe_quote(value):
        if value and any(ord(char) > 127 for char in value):
            return quote(value)
        return value
    
    # 对中文字段进行URL编码
    response.set_cookie(key="SessionId", value=SessionId, httponly=True, samesite="Lax")
    response.set_cookie(key="UserId", value=str(user.UserId), httponly=True, samesite="Lax")
    response.set_cookie(key="UserName", value=quote(user.UserName), httponly=True, samesite="Lax")  # 编码
    response.set_cookie(key="Role", value=quote(user.Role), httponly=True, samesite="Lax")  # 编码
    response.set_cookie(key="RealName", value=quote(user.RealName), httponly=True, samesite="Lax")  # 编码
    response.set_cookie(key="Contact", value=quote(user.Contact), httponly=True, samesite="Lax")  # 编码
    
    return response

@router.get("/logout")
async def logout():
    response = RedirectResponse(url="/")
    response.delete_cookie("SessionId")
    response.delete_cookie("UserId")
    response.delete_cookie("UserName")
    response.delete_cookie("Role")
    response.delete_cookie("RealName")
    response.delete_cookie("Contact")
    return response

@router.get("/welcome", response_class=HTMLResponse)
async def welcome_page(
    request: Request,
    SessionId: Optional[str] = Cookie(None),
    UserName: Optional[str] = Cookie(None),
    db: Session = Depends(get_db)
):
    # 解码用户名
    decoded_username = unquote(UserName) if UserName else None
    
    if not SessionId or not decoded_username or not validate_session(SessionId, decoded_username):
        return RedirectResponse(url="/?error=请先登录")
         
    return templates.TemplateResponse("welcome.html", {
        "request": request,
        "UserName": decoded_username  # 使用解码后的用户名
    })